<script setup lang="ts">
import type { FinancePaymentApplication } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { computed, ref } from 'vue'
import { getFinanceAttachmentByPage, getFinancePaymentApplicationById } from '@/api/finance'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useSystemStore } from '@/store/system'
import { formatDate } from '@/utils/timeUtils'
import { FileType, getFileType, previewDocument } from '@/utils/uploadFile'

definePage({
  style: {
    backgroundColor: '#f5f5f5',
    navigationBarTitleText: '付款申请详情',
    enablePullDownRefresh: true,
  },
})

const error = ref<string | null>(null)
const paymentData = ref<FinancePaymentApplication | null>(null)
const activeTab = ref('1')
const idValue = ref('')
const flowIdValue = ref('')

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
  navigateToProcessRecords,
} = useFlow()

// 使用系统store
const systemStore = useSystemStore()

// 基本信息
const basicInfo = computed<InfoItem[]>(() => {
  if (!paymentData.value)
    return []

  return [
    {
      label: '申请单号',
      value: paymentData.value.paymentNo || '-',
      key: 'paymentNo',
    },
    {
      label: '申请金额',
      value: paymentData.value.amount ? paymentData.value.amount.toFixed(2) : '0.00',
      key: 'amount',
      type: 'currency',
    },
    {
      label: '业务机构',
      value: paymentData.value.businessInstitutionName || '-',
      key: 'businessInstitutionName',
    },
    {
      label: '业务部门',
      value: paymentData.value.businessDepartmentName || '-',
      key: 'businessDepartmentName',
    },
    {
      label: '申请人',
      value: paymentData.value.applicantName || '-',
      key: 'applicantName',
    },
    {
      label: '申请时间',
      value: formatDate(paymentData.value.createTime, 'datetime_short'),
      key: 'createTime',
    },
    {
      label: '申请类型',
      value: paymentData.value.applicationType || '-',
      key: 'applicationType',
    },
    {
      label: '支付方式',
      value: paymentData.value.receiveType || '-',
      key: 'receiveType',
    },
    {
      label: '费用类型',
      value: paymentData.value.receiptEvent || '-',
      key: 'receiptEvent',
    },
    {
      label: '申请事由',
      value: paymentData.value.description || '-',
      key: 'description',
      forceMultiline: true,
    },
    {
      label: '附件信息',
      value: paymentData.value.financeAttachmentList || '-',
      key: `financeAttachmentList`,
      slot: 'financeAttachmentList',
      forceMultiline: true,
    },
  ]
})

// 结算信息
const settlementInfo = computed<InfoItem[]>(() => {
  if (!paymentData.value)
    return []

  return [
    {
      label: '付款主体',
      value: paymentData.value.payerEntity || '-',
      key: 'payerEntity',
      forceMultiline: true,
    },
    {
      label: '收款方',
      value: paymentData.value.receiveEntity || '-',
      key: 'receiveEntity',
      forceMultiline: true,
    },
    {
      label: '银行名称',
      value: paymentData.value.receiveBank || '-',
      key: 'receiveBank',
    },
    {
      label: '银行账号',
      value: paymentData.value.receiveAccount || '-',
      key: 'receiveAccount',
    },
    {
      label: '付款方式',
      value: systemStore.logisticsPayTypeDict.find(item => item.value === paymentData.value.paymentMethod)?.label || '-',
      key: 'paymentMethod',
    },
    {
      label: '是否全额核销',
      value: getStatusName('isFullWriteOff', paymentData.value.isFullWriteOff) || '-',
      key: 'isFullWriteOff',
    },
  ]
})

// 创建人信息
const creatorInfo = computed<InfoItem[]>(() => {
  if (!paymentData.value)
    return []

  return [
    {
      label: '审批状态',
      value: getStatusName('approvalStatus', paymentData.value.approvalStatus) || '-',
      key: 'approvalStatus',
    },
    {
      label: '创建人',
      value: paymentData.value.createName || '-',
      key: 'createName',
    },
    {
      label: '创建时间',
      value: formatDate(paymentData.value.createTime),
      key: 'createTime',
      type: 'date',
    },
    {
      label: '最后更新人',
      value: paymentData.value.updateName || '-',
      key: 'updateName',
    },
    {
      label: '最后更新时间',
      value: formatDate(paymentData.value.updateTime),
      key: 'updateTime',
      type: 'date',
    },
  ]
})

// 添加关联账单信息
const expenseDetailCards = computed<InfoItem[][]>(() => {
  if (!paymentData.value?.settlementInfoVoList)
    return []

  return paymentData.value.settlementInfoVoList.map((item, index) => [

    {
      label: '账单号',
      value: item.settlementNo || '-',
      key: `detail-${item.id || index}-settlementNo`,
    },
    {
      label: '运单号',
      value: item.waybillNo,
      key: `detail-${item.id || index}-waybillNo`,
    },
    {
      label: '申请金额',
      value: item.amount || '-',
      key: `detail-${item.id || index}-amount`,
      type: 'currency',
    },
    {
      label: '费用类目',
      value: item.costName || '-',
      key: `detail-${item.id || index}-costName`,
    },
    {
      label: '已付金额',
      value: item.invoiceAmount || '0',
      key: `detail-${item.id || index}-invoiceAmount`,
      type: 'currency',
    },
    {
      label: '应付金额',
      value: item.payment || '-',
      key: `detail-${item.id || index}-payment`,
      type: 'currency',
    },
    {
      label: '是否全额核销',
      value: getStatusName('isFullWriteOff', item.isFullWriteOff) || '-',
      key: `detail-${item.id || index}-isFullWriteOff`,
    },
    {
      label: '结算状态',
      value: getStatusName('isPay', item.isPay) || '-',
      key: `detail-${item.id || index}-isPay`,
    },
    {
      label: '开票状态',
      value: getStatusName('isInvoice', item.isInvoice) || '-',
      key: `detail-${item.id || index}-isInvoice`,
    },
  ])
})

// 获取付款申请详情
async function fetchPaymentDetail() {
  try {
    flowLoading.value = true
    error.value = null
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    const res = await getFinancePaymentApplicationById(currentProcess.value.businessKey)
    paymentData.value = res.data || null
    await loadAttachmentInfo(currentProcess.value.businessKey)
  }
  catch (err) {
    error.value = '获取付款申请详情失败'
    console.error('获取付款申请详情失败:', err)
  }
  finally {
    flowLoading.value = false
  }
}

// 获取附件列表信息
async function loadAttachmentInfo(id: string) {
  try {
    const res = await getFinanceAttachmentByPage({
      applicationId: id,
      applicationType: '付款',
      timestamp: Date.now(),
    })
    if (res.data?.records) {
      paymentData.value.financeAttachmentList = res.data.records || []
    }
    else {
      paymentData.value.financeAttachmentList = []
    }
  }
  catch (error) {
    console.error('获取附件信息失败:', error)
  }
}

// 初始化时获取详情
onLoad((e) => {
  // 初始化付款方式和支付方式字典
  systemStore.fetchPaymentTypeDict()
  systemStore.fetchLogisticsPayTypeDict()

  if (e.id) {
    idValue.value = e.id
  }
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  fetchPaymentDetail()
})

// 下拉刷新数据
onPullDownRefresh(async () => {
  await fetchPaymentDetail()
  uni.stopPullDownRefresh()
})
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 基本信息标签页 -->
    <wd-tabs v-model="activeTab" swipeable animated sticky :offset-top="0">
      <wd-tab title="基本信息" custom-class="bg-[#f9fafb] p-4">
        <!-- 基本信息 -->
        <DetailCard
          title="基本信息"
          :info-list="basicInfo"
        >
          <template #financeAttachmentList="{ value }">
            <view v-for="(item, i) in value" :key="`finance-attachment-${i}`" class="mr-2 h-25 w-25 overflow-hidden border border-blue-200 rounded-2 border-solid">
              <wd-img v-if="getFileType(item.fileName) === FileType.IMAGE" :src="item.filePath" lazy-load enable-preview mode="scaleToFill" class="h-full w-full" />
              <wd-img v-else-if="getFileType(item.fileName) === FileType.VIDEO" :src="item.filePath" lazy-load mode="scaleToFill" class="h-full w-full" />
              <wd-img v-else-if="getFileType(item.fileName) === FileType.AUDIO" :src="item.filePath" lazy-load mode="scaleToFill" class="h-full w-full" />
              <wd-img v-else-if="getFileType(item.fileName) === FileType.DOCUMENT" src="../../static/images/DOCUMENT.png" lazy-load mode="scaleToFill" class="h-full w-full" @click="previewDocument(item.filePath)" />
              <wd-img v-else :src="item.filePath" lazy-load enable-preview mode="scaleToFill" class="h-full w-full" />
            </view>
          </template>
        </DetailCard>

        <!-- 收款信息卡片 -->
        <DetailCard
          title="收款信息"
          :info-list="settlementInfo"
        />
        <DetailCard
          title="创建人信息"
          :info-list="creatorInfo"
        />
      </wd-tab>

      <!-- 创建人信息标签页 -->
      <wd-tab title="账单明细" custom-class="bg-[#f9fafb] p-4">
        <view v-for="(card, index) in expenseDetailCards" :key="index">
          <DetailCard
            :title="`账单明细${index + 1}`"
            :info-list="card"
          />
        </view>
      </wd-tab>
    </wd-tabs>

    <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
  </view>
</template>

<style scoped>
.page {
  padding-bottom: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}
</style>
